#!/bin/bash

function delete()
{
    rm -rf test_wal2json
}

function database_install()
{
    echo "init openGauss database"
    gs_initdb -D test_wal2json/dn1 --nodename=single_node1 -w Test@123 > init.log 2>&1
    if [ $? -ne 0 ]
    then
        echo "init failed, see init.log for detail information"
    delete
        exit 1
    else
        echo "init success, begin to start"
    fi
    echo "port = 25632" >> test_wal2json/dn1/postgresql.conf
    echo "most_available_sync = on" >> test_wal2json/dn1/postgresql.conf
    echo "replconninfo1 = 'localhost=127.0.0.1 localport=12001 localheartbeatport=12004 remotehost=127.0.0.1 remoteport=12002 remoteheartbeatport=12005'" >> test_wal2json/dn1/postgresql.conf
    sed -i 's/wal_level = hot_standby/wal_level = logical/g' test_wal2json/dn1/postgresql.conf
    sed -i 's/max_replication_slots = 8/max_replication_slots = 10/g' test_wal2json/dn1/postgresql.conf
    sed -i 's/max_wal_senders = 4/max_wal_senders = 10/g' test_wal2json/dn1/postgresql.conf
    gs_ctl start -D test_wal2json/dn1 -M primary > start.log 2>&1
    if [ $? -ne 0 ]
    then
        echo "start failed，see start.log for detail information"
    delete
        exit 1
    else
        echo "openGauss start success，the port is 25632"
    fi
}

function run_check()
{
    gsql -d postgres -p 25632 -c "create database regression;"
    if [ $? -ne 0 ]
    then
        echo "create database failed"
	delete
        exit 1
    fi
    if [ ! -d "result" ]; then    
        mkdir result
    fi

    for sql_flle in $( ls sql/|awk -F '.' '{print $1;}')
    do
        gsql -d regression -p 25632 -a <  sql/$sql_flle.sql > result/$sql_flle.out 2>&1
    done

    if [ -e "diff.log" ]; then
        rm diff.log
    fi

    for out_file in $(ls expected)
    do
        diff -u expected/$out_file result/$out_file >> diff.log
    done

    if [[ `cat diff.log |wc -l` -eq 0 ]]
    then
        echo -e "\033[32m OK \033[0m"
    else
        echo -e "\033[31m FAILED \033[0m"
    fi
    pid=$(ps ux | grep "test_wal2json" | grep -v "grep" | tr -s ' ' | cut -d ' ' -f 2)
    kill -9 $pid
    delete
    rm init.log
    rm start.log
}

function main()
{
    database_install
    run_check
}

main $@
